package model

import (
	"gin-build/hanlder/request"

	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	UserId   int    `gorm:"type:int" json:"userId"`
	Username string `gorm:"type:varchar(50);not null;"`
	Password string `gorm:"type:char(32);not null;"`
}

// 通过用户姓名查找
func (u *User) GetUserByUsername(db *gorm.DB, username string) error {
	return db.Where("username=?", username).Limit(1).Find(&u).Error
}

// 根据用户id 查询数据
func (u *User) GetUserId(db *gorm.DB, Id int) error {
	return db.Where("id=?", Id).Limit(1).First(&u).Error
}

// 添加用户
func (u *User) CreatUser(db *gorm.DB) error {
	return db.Create(&u).Error
}
func UsernameList(db *gorm.DB, req request.UsernameList) ([]User, int64, error) {
	var user []User
	var total int64
	query := db.Where("username like ?", "%"+req.Username+"%")
	if err := query.Model(&User{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}
	offset := (req.Page - 1) * req.Size
	if err := query.Offset(offset).Limit(req.Size).Find(&user).Error; err != nil {
		return nil, 0, err
	}
	return user, total, nil
}

type Friend struct {
	UserId   int `gorm:"type:int" json:"userId"`
	FriendId int `gorm:"type:int" json:"friendId"`
	Status   int `gorm:"not null;default 0;comment:状态 0:已申请,1:已通过"`
}

// 添加好友
func (f *Friend) AddFriend(db *gorm.DB) error {
	return db.Create(&f).Error
}

// 判断是否是好友
func (f *Friend) IsFriend(db *gorm.DB, userId int, friendId int) bool {
	var count int64
	db.Where("user_id=? and friend_id=?", userId, friendId).Count(&count)
	return count > 0
}
